package StudyCode.summary.BufferAndChannel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class WritingChannelWithByteBuffer {
	public static void main(String[] args) {
		try {
			WritableByteChannel channel = new FileOutputStream("E:/Copy/2.txt")
					.getChannel();

			ByteBuffer buf = ByteBuffer.allocateDirect(10);

			byte[] bytes = new byte[1024];
			int count = 0;
			int index = 0;
			FileInputStream inputStream = new FileInputStream("E:/Copy/1.txt");

			while (count >= 0) {
				if (index == count) {
					count = inputStream.read(bytes);
					index = 0;
				}

				while (index < count && buf.hasRemaining()) {
					buf.put(bytes[index++]);
				}

				buf.flip();

				int numWritten = channel.write(buf);

				if (buf.hasRemaining()) {
					buf.compact();
				} else {
					buf.clear();
				}
			}
			channel.close();
			System.out.println("使用 ByteBuffer 将数据写入到 Channel完成");
		} catch (Exception ignored) {
		}
	}
}
